package org.example.reemploymentsys.service;

import org.example.reemploymentsys.entity.ExamQuestion;
import org.example.reemploymentsys.entity.Organization;
import org.example.reemploymentsys.entity.UserTb;
import org.example.reemploymentsys.repository.ExamQuestionRe;
import org.example.reemploymentsys.repository.OrganizationRe;
import org.example.reemploymentsys.repository.UserTbRe;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class ExamQuestionService {

    @Autowired
    private ExamQuestionRe examQuestionRepository;
    @Autowired
    private UserTbRe userTbRe;
    @Autowired
    private OrganizationRe organizationRe;

    // 获取试题列表，支持分页和条件查询
    public Page<ExamQuestion> getExamQuestions(String username,int page, int pageSize, String questionType) {
        PageRequest pageRequest = PageRequest.of(page - 1, pageSize);
        UserTb user = userTbRe.findUserByUsername(username);
        String OrganizationId= userTbRe.findOrgizationIdByUsername(username);
        Organization organization = organizationRe.findOrganizationById(OrganizationId);
        if (questionType != null && !questionType.isEmpty()) {
            //Page<ExamQuestion> examQuestions=examQuestionRepository.findByUserOrOrganizationAndQuestionType(user,organization, questionType, pageRequest);
            return examQuestionRepository.findByUserOrOrganizationAndQuestionType(user,organization, questionType, pageRequest);
        }
        return examQuestionRepository.findByUserOrOrganization(user,organization,pageRequest);
    }

    // 添加试题
    public ExamQuestion addExamQuestion(String username,ExamQuestion examQuestion) {
        String OrganizationId= userTbRe.findOrgizationIdByUsername(username);
        Organization organization = organizationRe.findOrganizationById(OrganizationId);
        examQuestion.setOrganization(organization);
        return examQuestionRepository.save(examQuestion);
    }

    // 编辑试题
    public ExamQuestion editExamQuestion(Long id, ExamQuestion examQuestion) {
        if (examQuestionRepository.existsById(id)) {
            examQuestion.setId(id); // 设置 ID，确保更新时不会改变 ID
            return examQuestionRepository.save(examQuestion);
        }
       return null;
    }

    // 删除试题
    public String deleteExamQuestion(Long id) {
        try {
            examQuestionRepository.deleteById(id);
            return "true";
        } catch (Exception e){
           return e.getMessage();
        }
    }
}

